package liuliu.throughwaring.control.login;

import android.content.Context;

import net.tsz.afinal.FinalDb;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import liuliu.custom.method.Utils;
import liuliu.custom.model.Cryptography;
import liuliu.throughwaring.control.task.QueryTask;
import liuliu.throughwaring.control.task.addTask;
import liuliu.throughwaring.model.TerminalModel;

/**
 * Created by liuliu on 2015/11/11   11:32
 * 登录的接口
 *
 * @author 柳伟杰
 * @Email 1031066280@qq.com
 */
public class LoginListener {
    ILoginView mLoginView;
    Context mContext;
    FinalDb mDB;
    addTask task;

    public LoginListener(ILoginView loginView, Context context, FinalDb db) {
        this.mLoginView = loginView;
        this.mContext = context;
        this.mDB = db;
        task = new addTask(mContext);
    }

    public void login(String password) {
        List<TerminalModel> list = mDB.findAll(TerminalModel.class);
        TerminalModel terminalModel;
        if (list.size() > 0) {
            terminalModel = list.get(0);
            try {
                if (Cryptography.hashPassword(password).equals(terminalModel.getTerminalPassword())) {
                    mLoginView.OnLoginResult(true, "");
                } else {
                    mLoginView.OnLoginResult(false, "账号或密码错误，请重新输入！");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        } else {
            mLoginView.OnLoginResult(false, "登录失败！");
        }
    }

    //绑定民警
    public void updatePolice() {
        task.UpdateTerminalPolice(mLoginView);
    }
}
